<template>
  <div class="main">
    <div class="air-column">
      <h2>乘机人</h2>
      <el-form ref="memberForm" class="member-info" :model="{users}">
        <div v-for="(user, index) of users" :key="user.uid" class="member-info-item">
          <el-form-item
            label="乘机人类型"
            :prop="`users[${index}].username`"
            :rules="[{
              required: true,
              message: '请输入乘机人名字',
              trigger: 'blur'
            }]"
          >
            <el-input v-model="user.username" placeholder="姓名" class="input-with-select">
              <el-select
                slot="prepend"
                value="1"
                placeholder="请选择"
              >
                <el-option label="成人" value="1" />
              </el-select>
            </el-input>
          </el-form-item>

          <el-form-item
            label="证件类型"
            :prop="`users[${index}].id`"
            :rules="[{
              required: true,
              message: '请输入正确的身份证号码',
              trigger: 'blur',
              pattern: /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
            }]"
          >
            <el-input
              v-model="user.id"
              placeholder="证件号码"
              class="input-with-select"
            >
              <el-select
                slot="prepend"
                value="1"
                placeholder="请选择"
              >
                <el-option label="身份证" value="1" :checked="true" />
              </el-select>
            </el-input>
          </el-form-item>

          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers">
        添加乘机人
      </el-button>
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <el-checkbox-group v-model="insurances">
          <div v-for="item of data.insurances" :key="item.id" class="insurance-item">
            <el-checkbox
              :label="item.id"
              border
            >
              {{ `${item.type}：￥${item.price}/份×${users.length}  最高赔付${item.compensation}` }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
    </div>

    <div class="air-column">
      <h2>发票</h2>
      <el-switch v-model="invoice" />
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form
          ref="linkmanForm"
          label-width="80px"
          :model="{contactName,contactPhone,captcha}"
          :rules="linkmanRules"
        >
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="contactName" />
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input v-model="contactPhone" placeholder="请输入内容">
              <template slot="append">
                <el-button @click="handleSendCaptcha">
                  发送验证码
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="captcha" />
          </el-form-item>
        </el-form>
        <el-button type="warning" class="submit" @click="handleSubmit">
          提交订单
        </el-button>
      </div>
    </div>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <span>未登录，请先登录</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toLogin">去登录</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'OrderForm',
  props: {
    data: {
      type: Object,
      default () {
        return {
        }
      }
    }
  },
  data () {
    return {
      dialogVisible: false,
      linkmanRules: {
        contactName: [{
          required: true,
          message: '用户名不能为空',
          trigger: 'blur'
        }],
        contactPhone: [{
          required: true,
          message: '请输入正确的手机号',
          trigger: 'blur',
          pattern: /^1[345678]\d{9}$/
        }],
        captcha: [{
          required: true,
          message: '请输入验证码',
          trigger: 'blur'
        }]
      },
      users: [{
        username: '哈哈哈',
        id: '441882199809133919',
        uid: Date.now() + Math.random()
      }],
      insurances: [],
      invoice: false,
      contactName: '嘿嘿',
      contactPhone: '13847474837',
      captcha: '',
      price: 0
    }
  },
  watch: {
    users () {
      this.$emit('usersChange', this.users.length)
    },
    insurances () {
      let insPrice = 0
      this.insurances.forEach((id) => {
        this.data.insurances.forEach((item) => {
          if (id === item.id) {
            insPrice += item.price * this.users.length
          }
        })
      })
      this.$emit('getInsPrice', insPrice)
    }
  },
  methods: {
    // 添加乘机人
    handleAddUsers () {
      this.users.push({
        username: '',
        id: '',
        uid: Date.now() + Math.random()
      })
    },

    // 移除乘机人
    handleDeleteUser (index) {
      this.users.splice(index, 1)
    },

    // 发送手机验证码
    handleSendCaptcha () {
      this.$axios.post('/captchas', {
        tel: this.contactPhone
      }).then((res) => {
        this.$message.success('验证码发送成功：' + res.data.code)
      })
    },

    // 提交订单
    handleSubmit () {
      // element-ui表单验证方法validate()如果不填入参数,则会返回一个promise，等待两个表单验证成功再发请求
      Promise.all([this.$refs.memberForm.validate(), this.$refs.linkmanForm.validate()])
        .then((res) => {
          if (res[0] && res[1]) {
            this.sendFormRequst()
          }
        }).catch(() => {
          this.$message.error('请填写完整信息')
        })
    },
    sendFormRequst () {
      if (!this.$store.state.userInfo.token) {
        this.dialogVisible = true
        return
      }
      const data = {
        users: this.users,
        insurances: this.insurances,
        invoice: this.invoice,
        seat_xid: this.$route.query.seat_xid,
        air: this.$route.query.id,
        captcha: this.captcha,
        contactName: this.contactName,
        contactPhone: this.contactPhone
      }
      this.loading = true
      this.$axios({
        url: '/airorders',
        method: 'post',
        headers: {
          Authorization: 'Bearer ' + this.$store.state.userInfo.token
        },
        data
      }).then((res) => {
        this.$router.push('/air/pay?id=' + res.data.data.id)
      })
    },
    toLogin () {
      this.dialogVisible = false
      this.$router.push({
        name: 'user',
        params: {
          from: 'order',
          query: this.$route.query
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.air-column{
        border-bottom:1px #ddd dashed;
        padding-bottom: 20px;
        margin-bottom: 20px;
    }

    .air-column h2{
        margin-bottom: 20px;
        font-size: 22px;
        font-weight: normal;
    }

    /deep/ .el-select .el-input {
        width: 130px;
    }

    .input-with-select{
        width:590px;
    }

    .input-with-select /deep/  .el-input-group__prepend {
        background-color: #fff;
    }
    .member-info /deep/ .el-form-item{
        margin-bottom:10px;
    }

    .member-info-item{
        border-bottom:1px #eee dashed;
        padding-bottom: 20px;
        position: relative;

        &:first-child{
            .delete-user{
                display: none;
            }
        }
    }

    .add-member{
        margin-top:20px;
    }

    .delete-user{
        display: block;
        background:#ddd;
        width:16px;
        height:16px;
        font-size:14px;
        text-align: center;
        line-height: 16px;
        color:#fff;
        cursor: pointer;
        border-radius: 50px;
        position:absolute;
        right:-30px;
        top:50%;
    }

    .insurance{
        > div{
            margin-top:10px;
        }
    }

    .insurance-item{
        margin-bottom: 20px;
    }

    .contact{
        /deep/ .el-input{
            width:50%;
        }
    }

    .submit{
        margin: 50px auto;
        display: block;
        width:250px;
        height:50px;
    }
</style>
